import { Input, Popover, Segmented, Tabs } from "antd";
import { useDispatch } from "react-redux";
import type { InputRef, TabsProps } from "antd";
import {
  FireOutlined,
  FieldTimeOutlined,
  LikeOutlined,
  CommentOutlined,
  CaretDownOutlined,
} from "@ant-design/icons";
import CommentLess from "./index.module.less";
import { useEffect, useState, forwardRef, useImperativeHandle } from "react";
import { countItems } from "@/utils/PublicFunction";
import { useSelector } from "react-redux";
import data from "@emoji-mart/data";
import { ChildrenCommentType } from "./util/type";
import { showModal } from "@/store/modules/user";
import Picker from "@emoji-mart/react";
const Comment = forwardRef(
  (
    {
      commentList,
      commentLength,
      AuthorMessage,
      ShowAll,
      ArticleInfo,
      onsetCommentList,
      FusendCommentMethods,
      showAllCommentList,
      LikeComment,
    }: any,
    ref
  ) => {
    const dispatch = useDispatch();
    const UserId = useSelector((state: any) => state.user.UserId);
    const HeaderImg = useSelector((state: any) => state.user.HeaderImg);
    const { TextArea } = Input;
    const [commentValue, setcommentValue] = useState("");
    const [emojiInputType, setemojiInputType] = useState("");
    const [emojiClickContent, setemojiClickContent] = useState({});
    const [showSend, setshowSend] = useState(false);
    useImperativeHandle(ref, () => ({
      ClearFuInput,
    }));
    const Tabitems = [
      {
        key: "1",
        label: "最热",
      },
      {
        key: "2",
        label: "最新",
      },
    ];
    const onChangeTabs = (e: any) => {
      console.log(33, e);
    };
    const CommentClick = (commentItem: any) => {
      console.log(commentItem, "点击", commentList);
      //先将全部评论的输入框显示置为false
      const updatedCommentList = commentList.map((item: any) => {
        // 修改当前项的InputShow属性
        if (commentItem.CommentId === item.CommentId) {
          item.InputShow = true;
        } else if (
          commentItem.CommentId !== item.CommentId &&
          item.InputContent === ""
        ) {
          item.InputShow = false;
        }
        // 如果存在子项(Children)，则递归处理子项
        if (item.Children) {
          item.Children = item.Children.map((child: any) => {
            if (commentItem.CommentId === child.CommentId) {
              child.InputShow = true;
            } else if (
              commentItem.CommentId !== child.CommentId &&
              child.InputContent === ""
            ) {
              child.InputShow = false;
            }
            return child;
          });
        }

        // 返回修改后的项
        return item;
      });
      onsetCommentList(updatedCommentList);
    };
    const CommentCancal = (commentItem: any) => {
      console.log(commentItem, "点击", commentList);
      //先将全部评论的输入框显示置为false
      const updatedCommentList = commentList.map((item: any) => {
        // 修改当前项的InputShow属性
        if (commentItem.CommentId === item.CommentId) {
          item.InputShow = false;
          item.InputContent = "";
        }
        // 如果存在子项(Children)，则递归处理子项
        if (item.Children) {
          item.Children = item.Children.map((child: any) => {
            if (commentItem.CommentId === child.CommentId) {
              child.InputShow = false;
              child.InputContent = "";
            }
            return child;
          });
        }

        // 返回修改后的项
        return item;
      });
      onsetCommentList(updatedCommentList);
    };

    const [commentPlaceholder, setcommentPlaceholder] =
      useState("抢首评，友善交流");
    const selectEmoji = (e: any) => {
      console.log(3333, e);
      if (emojiInputType === "FuchildrenEmoji") {
        const newChatContent =
          commentValue.length > 0 ? commentValue + e.native : e.native;
        setcommentValue(newChatContent);
      } else if (emojiInputType === "childrenEmoji") {
        setListcommentValueEmoji(emojiClickContent, e);
      }
    };
    const setListcommentValue = (itemAll: any, e: any) => {
      console.log(4444444, itemAll.CommentId, e);
      const updatedCommentList = commentList.map((item: any) => {
        // 修改当前项的InputShow属性
        if (itemAll.CommentId === item.CommentId) {
          item.InputContent = e;
        }
        // 如果存在子项(Children)，则递归处理子项
        if (item.Children) {
          item.Children = item.Children.map((child: any) => {
            if (itemAll.CommentId === child.CommentId) {
              child.InputContent = e;
            }
            return child;
          });
        }
        // 返回修改后的项
        return item;
      });
      onsetCommentList(updatedCommentList);
    };

    const setListcommentValueEmoji = (itemAll: any, e: any) => {
      console.log(4444444, itemAll.CommentId, e);
      const emojiupdatedCommentList = commentList.map((item: any) => {
        // 修改当前项的InputShow属性
        if (itemAll.CommentId === item.CommentId) {
          item.InputContent =
            item.InputContent.length > 0
              ? item.InputContent + e.native
              : e.native;
        }
        // 如果存在子项(Children)，则递归处理子项
        if (item.Children) {
          item.Children = item.Children.map((child: any) => {
            if (itemAll.CommentId === child.CommentId) {
              child.InputContent =
                child.InputContent.length > 0
                  ? child.InputContent + e.native
                  : e.native;
            }
            return child;
          });
        }
        // 返回修改后的项
        return item;
      });
      onsetCommentList(emojiupdatedCommentList);
    };

    //发送评论
    const FusendComment = async (FatherCommentId: any, AtUserId: any) => {
      const commentInfo = {
        CommentContent: commentValue,
        FatherCommentId: FatherCommentId,
        AtUserId: AtUserId,
      };
      FusendCommentMethods(commentInfo);
    };
    const ChildsendComment = (Fuitem: any, item: any) => {
      console.log("子", Fuitem, item);
      if (Object.keys(item).length === 0) {
        var commentInfo = {
          CommentContent: Fuitem.InputContent,
          FatherCommentId: Fuitem.CommentId,
          AtUserId: Fuitem.CreateUserId || "",
        };
      } else {
        var commentInfo = {
          CommentContent: item.InputContent,
          FatherCommentId: Fuitem.CommentId,
          AtUserId: item.CreateUserId || "",
        };
      }

      FusendCommentMethods(commentInfo);
    };
    //清空父级输入框的值
    const ClearFuInput = () => {
      setcommentValue("");
    };
    const content = (
      <Picker
        data={data}
        onEmojiSelect={selectEmoji}
        locale={"zh"}
        set={"native"}
        previewPosition={"none"}
        searchPosition={"none"}
      />
    );

    const emojiClick = (item: any) => {
      console.log("emoji", item);
      setemojiInputType("childrenEmoji");
      setemojiClickContent(item);
    };

    const FuemojiClick = () => {
      setemojiInputType("FuchildrenEmoji");
      setemojiClickContent({});
    };

    useEffect(() => {
      if (commentValue.length > 0) {
        setshowSend(true);
      } else {
        setshowSend(false);
      }
    }, [commentValue]);

    return (
      <>
        <div className={CommentLess.comment_content}>
          <div className="TitleAnd_Num">
            <div className="name_add_name">评论</div>
            <div className="num">{countItems(commentLength)}</div>
          </div>
          <div className="comment_input">
            <div className="left_headerimg">
              {HeaderImg ? (
                <img src={HeaderImg} alt="" />
              ) : (
                <img src="../../../public/icon/headerimgNo.svg" alt="" />
              )}
            </div>
            {HeaderImg ? (
              <div className="right_input">
                <TextArea
                  showCount
                  maxLength={1000}
                  value={commentValue}
                  onChange={(e) => setcommentValue(e.target.value)}
                  placeholder={commentPlaceholder}
                  variant="filled"
                />
                <div className="input_other_components">
                  <Popover placement="bottom" content={content} trigger="click">
                    <div className="left_emoji" onClick={FuemojiClick}>
                      <svg
                        t="1710924077331"
                        className="icon"
                        viewBox="0 0 1024 1024"
                        version="1.1"
                        xmlns="http://www.w3.org/2000/svg"
                        p-id="2654"
                        width="20"
                        height="20"
                      >
                        <path
                          d="M512 64c247.136 0 448 200.864 448 448s-200.864 448-448 448S64 759.136 64 512 264.864 64 512 64z m0 832c211.968 0 384-172.032 384-384S723.968 128 512 128 128 300.032 128 512s172.032 384 384 384z m96-480a64 64 0 1 1 128 0 64 64 0 0 1-128 0zM288 416a64 64 0 1 1 128 0 64 64 0 0 1-128 0z m407.68 170.848c17.184 11.2 22.4 34.336 11.2 51.52A229.44 229.44 0 0 1 512 745.152a229.44 229.44 0 0 1-194.88-106.784 37.408 37.408 0 0 1 11.2-51.52 37.408 37.408 0 0 1 51.52 11.2A155.904 155.904 0 0 0 512 670.464c53.76 0 103.04-26.88 132.16-72.416 11.2-17.184 34.336-22.4 51.52-11.2z"
                          fill="#8a919f"
                          p-id="2655"
                        ></path>
                      </svg>
                    </div>
                  </Popover>
                  <div
                    className="right_btn"
                    onClick={() => FusendComment("", "")}
                  >
                    <div
                      className={[
                        showSend ? "send_btn_active" : "",
                        "send_btn",
                      ].join(" ")}
                    >
                      发送
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <div className="right_input_no">
                <div className="center_content">
                  <div className="btn" onClick={() => dispatch(showModal())}>
                    登录/注册
                  </div>
                  <div className="tips">即可发布评论!</div>
                </div>
              </div>
            )}
          </div>
          <div className="tab_sort">
            <Tabs
              defaultActiveKey="1"
              items={Tabitems}
              onChange={onChangeTabs}
            />
          </div>
          <div className="comment_others_list">
            <div className="comment_list">
              {commentList.map((item: any) => {
                return (
                  <>
                    <div className="first_comment_items" key={item.CommentId}>
                      <div className="left_first_headerimg">
                        <img src={item.HeaderImg} alt="" />
                      </div>
                      <div className="right_comment_info">
                        <div className="user_name">
                          <div>{item.CommentUserName}</div>
                          {Number(item.CreateUserId) === Number(UserId) ? (
                            <div className="author_is">作者</div>
                          ) : (
                            ""
                          )}
                        </div>
                        <div className="user_comment_content">
                          {item.CommentContent}
                        </div>
                        <div className="other_info">
                          <div className="time">{item.CreateTime}</div>
                          <div
                            className="like"
                            onClick={() => LikeComment(item)}
                          >
                            <LikeOutlined />
                            {item.LikeNum > 0 ? (
                              <span className="likeTitle">{item.LikeNum}</span>
                            ) : (
                              <span className="likeTitle">点赞</span>
                            )}
                          </div>
                          {item.InputShow ? (
                            <div
                              className="cancelcomment"
                              onClick={() => CommentCancal(item)}
                            >
                              <CommentOutlined />
                              &nbsp;取消回复
                            </div>
                          ) : (
                            <div
                              className="comment"
                              onClick={() => CommentClick(item)}
                            >
                              <CommentOutlined />
                              <div className="num">
                                {item.Children.length > 0
                                  ? item.Children.length
                                  : ""}
                              </div>
                            </div>
                          )}
                        </div>
                        {item.InputShow && (
                          <div className="input_all">
                            <TextArea
                              showCount
                              maxLength={1000}
                              value={item.InputContent}
                              onChange={(e) =>
                                setListcommentValue(item, e.target.value)
                              }
                              placeholder={commentPlaceholder}
                              variant="filled"
                            />
                            <div className="input_other_components">
                              <Popover
                                placement="bottom"
                                content={content}
                                trigger="click"
                              >
                                <div
                                  className="left_emoji"
                                  onClick={() => emojiClick(item)}
                                >
                                  <svg
                                    t="1710924077331"
                                    className="icon"
                                    viewBox="0 0 1024 1024"
                                    version="1.1"
                                    xmlns="http://www.w3.org/2000/svg"
                                    p-id="2654"
                                    width="20"
                                    height="20"
                                  >
                                    <path
                                      d="M512 64c247.136 0 448 200.864 448 448s-200.864 448-448 448S64 759.136 64 512 264.864 64 512 64z m0 832c211.968 0 384-172.032 384-384S723.968 128 512 128 128 300.032 128 512s172.032 384 384 384z m96-480a64 64 0 1 1 128 0 64 64 0 0 1-128 0zM288 416a64 64 0 1 1 128 0 64 64 0 0 1-128 0z m407.68 170.848c17.184 11.2 22.4 34.336 11.2 51.52A229.44 229.44 0 0 1 512 745.152a229.44 229.44 0 0 1-194.88-106.784 37.408 37.408 0 0 1 11.2-51.52 37.408 37.408 0 0 1 51.52 11.2A155.904 155.904 0 0 0 512 670.464c53.76 0 103.04-26.88 132.16-72.416 11.2-17.184 34.336-22.4 51.52-11.2z"
                                      fill="#8a919f"
                                      p-id="2655"
                                    ></path>
                                  </svg>
                                </div>
                              </Popover>
                              <div
                                className="right_btn"
                                onClick={() => ChildsendComment(item, "")}
                              >
                                <div
                                  className={[
                                    item.InputContent !== ""
                                      ? "send_btn_active"
                                      : "",
                                    "send_btn",
                                  ].join(" ")}
                                >
                                  发送
                                </div>
                              </div>
                            </div>
                          </div>
                        )}
                        {item.Children.map((childrenItem: any) => {
                          return (
                            <div
                              className="others_tow_more_comment_list"
                              key={childrenItem.CommentId}
                            >
                              <div className="left_img">
                                <img src={childrenItem.HeaderImg} alt="" />
                              </div>
                              <div className="right">
                                {childrenItem.AtUserName !== "" ? (
                                  <div className="name">
                                    <div> {childrenItem.CommentUserName}</div>
                                    {Number(childrenItem.CreateUserId) ===
                                    Number(UserId) ? (
                                      <div className="author_is">作者</div>
                                    ) : (
                                      ""
                                    )}
                                    <span
                                      style={{
                                        color: "black",
                                        margin: "0 5px",
                                      }}
                                    >
                                      回复
                                    </span>
                                    {childrenItem.AtUserName}：
                                  </div>
                                ) : (
                                  <div className="name">
                                    {" "}
                                    {childrenItem.CommentUserName}：
                                  </div>
                                )}
                                <div className="user_comment_content">
                                  {childrenItem.CommentContent}
                                </div>
                                <div className="other_info">
                                  <div className="time">
                                    {childrenItem.CreateTime}
                                  </div>
                                  <div
                                    className="like"
                                    onClick={() => LikeComment(item)}
                                  >
                                    <LikeOutlined />
                                    {childrenItem.LikeNum > 0 ? (
                                      <span className="likeTitle">
                                        {childrenItem.LikeNum}
                                      </span>
                                    ) : (
                                      <span className="likeTitle">点赞</span>
                                    )}
                                  </div>
                                  {childrenItem.InputShow ? (
                                    <div
                                      className="cancelcomment"
                                      onClick={() =>
                                        CommentCancal(childrenItem)
                                      }
                                    >
                                      <CommentOutlined />
                                      &nbsp;取消回复
                                    </div>
                                  ) : (
                                    <div
                                      className="comment"
                                      onClick={() => CommentClick(childrenItem)}
                                    >
                                      <CommentOutlined />
                                      <div className="num">回复</div>
                                    </div>
                                  )}
                                </div>
                                {childrenItem.InputShow && (
                                  <div className="input_all">
                                    <TextArea
                                      showCount
                                      maxLength={1000}
                                      value={childrenItem.InputContent}
                                      onChange={(e) =>
                                        setListcommentValue(
                                          childrenItem,
                                          e.target.value
                                        )
                                      }
                                      placeholder={commentPlaceholder}
                                      variant="filled"
                                    />
                                    <div className="input_other_components">
                                      <Popover
                                        placement="bottom"
                                        content={content}
                                        trigger="click"
                                      >
                                        <div
                                          className="left_emoji"
                                          onClick={() =>
                                            emojiClick(childrenItem)
                                          }
                                        >
                                          <svg
                                            t="1710924077331"
                                            className="icon"
                                            viewBox="0 0 1024 1024"
                                            version="1.1"
                                            xmlns="http://www.w3.org/2000/svg"
                                            p-id="2654"
                                            width="20"
                                            height="20"
                                          >
                                            <path
                                              d="M512 64c247.136 0 448 200.864 448 448s-200.864 448-448 448S64 759.136 64 512 264.864 64 512 64z m0 832c211.968 0 384-172.032 384-384S723.968 128 512 128 128 300.032 128 512s172.032 384 384 384z m96-480a64 64 0 1 1 128 0 64 64 0 0 1-128 0zM288 416a64 64 0 1 1 128 0 64 64 0 0 1-128 0z m407.68 170.848c17.184 11.2 22.4 34.336 11.2 51.52A229.44 229.44 0 0 1 512 745.152a229.44 229.44 0 0 1-194.88-106.784 37.408 37.408 0 0 1 11.2-51.52 37.408 37.408 0 0 1 51.52 11.2A155.904 155.904 0 0 0 512 670.464c53.76 0 103.04-26.88 132.16-72.416 11.2-17.184 34.336-22.4 51.52-11.2z"
                                              fill="#8a919f"
                                              p-id="2655"
                                            ></path>
                                          </svg>
                                        </div>
                                      </Popover>
                                      <div
                                        className="right_btn"
                                        onClick={() =>
                                          ChildsendComment(item, childrenItem)
                                        }
                                      >
                                        <div
                                          className={[
                                            childrenItem.InputContent !== ""
                                              ? "send_btn_active"
                                              : "",
                                            "send_btn",
                                          ].join(" ")}
                                        >
                                          发送
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                )}
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  </>
                );
              })}
            </div>
          </div>
          {!ShowAll && (
            <div className="show_more_commentList" onClick={showAllCommentList}>
              <div>
                查看剩余{countItems(commentLength) - countItems(commentList)}
                条评论
              </div>
              <CaretDownOutlined className="showMoreIcon" />
            </div>
          )}
        </div>
      </>
    );
  }
);

export default Comment;
